from utils.celery import app 
from datetime import datetime
from tortoise.transactions import in_transaction

from models.payment import Payment, OrderItemFake, OrderFake
from models.products import Product
from models.enums import PaymentStatus, OrderStatus


# 定时任务，检查超时未支付订单自动取消+释放库存
@app.task
async def check_payment_timeout():
    """检查超时未支付订单"""
    now = datetime.now()
    # 筛选：待支付+超时（timeout_at < 当前时间）的支付记录
    payments = await Payment.filter(
        pay_status=PaymentStatus.PENDING,
        timeout_at__lt=now
    ).prefetch_related("order")
    
    for payment in payments:
        async with in_transaction():
            # 1. 更新支付状态为超时
            payment.pay_status = PaymentStatus.TIMEOUT
            await payment.save()
            
            # 2. 更新订单状态为取消
            order = await payment.order
            if order.status == OrderStatus.PENDING:  # 仅待支付订单需要取消
                order.status = OrderStatus.CANCELLED
                order.cancelled_at = now
                await order.save()
                
                # 3. 释放库存（避免重复释放）
                items = await OrderItemFake.filter(order=order).prefetch_related("product")
                for item in items:
                    product = await item.product
                    product.inventory += item.quantity
                    await product.save()
    
    return f"处理{len(payments)}条超时支付记录"